package cn.bbs.ba.json;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.ibm.db2.jcc.b.ob;

import cn.bbs.ba.base.BaseDto;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

/**
 * JSON工具类，直接转换成MAP
 * @author SL400
 *
 */
public class JSONUntil {
	
	public static List<Map<String, Object>> parseJSON2List(String jsonStr){
		JSONObject jsonObj = JSONObject.fromObject(jsonStr);
		JSONArray jsonArr = jsonObj.getJSONArray("root");
        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        Iterator<JSONObject> it = jsonArr.iterator();
        while(it.hasNext()){
            JSONObject json2 = it.next();
            list.add(parseJSON2Map(json2.toString()));
        }
        return list;
    }
    
   
    public static BaseDto parseJSON2Map(String jsonStr){
        BaseDto map = new BaseDto();
        //最外层解析
        JSONObject json = JSONObject.fromObject(jsonStr);
        for(Object k : json.keySet()){
            Object v = json.get(k); 
            //如果内层还是数组的话，继续解析
            if(v instanceof JSONArray){
                List<BaseDto> list = new ArrayList<BaseDto>();
                Iterator<JSONObject> it = ((JSONArray)v).iterator();
                while(it.hasNext()){
                    JSONObject json2 = it.next();
                    list.add(parseJSON2Map(json2.toString()));
                }
                map.setValue(k.toString(), list);
            } else {
                map.setValue(k.toString(), mapToBaseDto((Map)v));
            }
        }
        return map;
    }
    
    /**
     * 
     */
    public static BaseDto mapToBaseDto(Map<Object, Object> map) {
    	BaseDto dto = new BaseDto();
    	Iterator iterator2=map.entrySet().iterator();   
    	while(iterator2.hasNext()){   
    		Map.Entry   entry= (Map.Entry)iterator2.next();   
    		dto.setValue((String)entry.getKey(), entry.getValue());
    	}
    	return dto;
    }
    
    public static List<Map<String, Object>> getListByUrl(String url){
        try {
            //通过HTTP获取JSON数据
            InputStream in = new URL(url).openStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder sb = new StringBuilder();
            String line;
            while((line=reader.readLine())!=null){
                sb.append(line);
            }
            return parseJSON2List(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
   
    public static Map<String, Object> getMapByUrl(String url){
        try {
            //通过HTTP获取JSON数据
            InputStream in = new URL(url).openStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder sb = new StringBuilder();
            String line;
            while((line=reader.readLine())!=null){
                sb.append(line);
            }
            return parseJSON2Map(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static String getJsonString4JavaPOJO(Object javaObj , String dataFormat){    
        
        JSONObject json;    
        JsonConfig jsonConfig = configJson(dataFormat);    
        json = JSONObject.fromObject(javaObj,jsonConfig);    
        return json.toString();    
            
            
    }   
    
    public static JsonConfig configJson(String datePattern){       
        JsonConfig jsonConfig = new JsonConfig();       
        jsonConfig.setExcludes(new String[]{""});       
        jsonConfig.setIgnoreDefaultExcludes(false);       
        jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);       
//        jsonConfig.registerJsonValueProcessor(Date.class,       
//            new DateJsonValueProcessor(datePattern));       
          
        return jsonConfig;       
    }      

    //test
    public static void main(String[] args) {
//        String url = "http://www.baidu.com";
//        List<Map<String,Object>> list = getListByUrl(url);
    	Map<String, Object> list2 = parseJSON2Map("{totalProperty:2,root:{aa:[{\"array\":\"123\",\"code\":\"321\",\"firstdepat\":\"网优\",\"id\":\"111\",\"name\":\"willis\",\"outtime\":\"5\",\"redtime\":\"4\",\"useable\":\"yes\",\"yellowtime\":\"3\"},{\"array\":\"123\",\"code\":\"321\",\"firstdepat\":\"网优\",\"id\":\"111\",\"name\":\"willis\",\"outtime\":\"5\",\"redtime\":\"4\",\"useable\":\"yes\",\"yellowtime\":\"3\"}]}} ");
//        List<Map<String, Object>> list2 = parseJSON2List("[{ 　name:\"中国\",　aaa:\"中国\" }]");
//    	list2.get("root");
        System.out.println(((Map)list2.get("root")).get("aa"));
    }

}
